package com.ihighest.app.infox.activity;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.ColumMainProductImgAdapter;
import com.ihighest.app.infox.adapter.ColumnListAdapter;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.HorizontialListView;
import com.ihighest.app.infox.tools.CheckNetWork;
import com.ihighest.app.infox.tools.InitShare;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 企业主页
 * 
 * @author lkx Created at 2015-10-10 上午10:32:20
 * @version 1.0
 */
public class CompanyPagesActivity extends BaseActivity implements OnClickListener {
	private ActivityTitle title;
	private ColumMainProductImgAdapter adapter;
	private HorizontialListView horizontialListview;
	private String cid, phonenumber, name, describe, imageurl; // 企业号id
	int peoplenumber;
	int page = 1;
	long time = 0;
	private JSONArray productJsonArray;
	private JSONArray contentJsonArray;
	private PullToRefreshListView listview;
	private ColumnListAdapter companyPagesAdapter;
	TextView call, ask;
	private String subscription;
	private String service;// kefuid

	ImageView imageview;
	TextView companyPagesSubscribeNumber, nameOfEnterprise, enterpriseSlogan, subcriptionTextView;
	private PopupWindow mPopupWindow;
	private SHARE_MEDIA shareTo;
	private InitShare share;
	private TextView moreTextView;
	private TextView emptyview;
	RelativeLayout relativeLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_companypage);
		title = (ActivityTitle) findViewById(R.id.CompanyPagesActivityTitle);

		title.setViewVersible(title.rightLayout, title.titleBack);
		title.setViewGone(title.titleSetting, title.titleRefresh, title.titleMsg, title.titleSearch);
		title.setOtherImg(R.drawable.infox_title_share);
		horizontialListview = (HorizontialListView) findViewById(R.id.MainProductsListView);
		share = new InitShare(this);
		listview = (PullToRefreshListView) findViewById(R.id.companyPagesActivityNewslist);

		emptyview = new TextView(CompanyPagesActivity.this);
		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		emptyview.setText("加载中...");
		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		emptyview.setVisibility(View.GONE);
		listview.setEmptyView(emptyview);

		moreTextView = (TextView) findViewById(R.id.textView3);
		call = (TextView) findViewById(R.id.servicrPhone);
		ask = (TextView) findViewById(R.id.consultationOfPreservice);

		imageview = (ImageView) findViewById(R.id.imageView1);
		companyPagesSubscribeNumber = (TextView) findViewById(R.id.companyPagesSubscribeNumber);
		nameOfEnterprise = (TextView) findViewById(R.id.nameOfEnterprise);
		enterpriseSlogan = (TextView) findViewById(R.id.enterpriseSlogan);
		subcriptionTextView = (TextView) findViewById(R.id.textView1);
		relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout2);
		getintentdata();

		getproduct();
		getcontent();
		companyPagesAdapter = new ColumnListAdapter(CompanyPagesActivity.this);
		listview.setAdapter(companyPagesAdapter);

		listview.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {

				if (CheckNetWork.isConnected(CompanyPagesActivity.this)) {
					page = 1;
					time = 0;
					getcontent();
				} else {
					ToastKit.showShort(CompanyPagesActivity.this, "请连接网络");
				}

			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {

				if (CheckNetWork.isConnected(CompanyPagesActivity.this)) {
					page++;
					getcontent();

				} else {
					ToastKit.showShort(CompanyPagesActivity.this, "请连接网络");
				}
			}

		});

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CompanyPagesActivity.this, InformationalContentActivity.class);
				try {
					intent.putExtra("newsId", contentJsonArray.getJSONObject(arg2 - 1).getString("id"));
					startActivity(intent);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
	}

	/**
	 * 
	 * 获取传递过来的内容
	 * 
	 * 
	 * @author yyh Created at 2015-11-11 下午4:33:58
	 */
	private void getintentdata() {
		cid = getIntent().getStringExtra("cid");

		Api.get("enterprise/details", ApiParam.create().addParam("id", cid), new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					try {
						name = result.getData().getString("title");
						describe = result.getData().getString("advertise");
						phonenumber = result.getData().getString("phone");
						peoplenumber = result.getData().getInt("count");
						imageurl = result.getData().getString("image");
						subscription = result.getData().getString("isSubscribes");

						ininView();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	/**
	 * 
	 * 加载企业内容列表
	 * 
	 * 
	 * @author yyh Created at 2015-11-11 下午3:15:26
	 */
	private void getcontent() {
		ApiParam param = ApiParam.create();
		param.addParam("cid", cid);
		param.addParam("page", page);

		Api.get("enterprise/infos", param, new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {

					if (page == 1) {
						if (result.getDatas() == null || result.getDatas().length() <= 0) {
							emptyview.setText("暂无数据");
						}

						contentJsonArray = result.getDatas();

						companyPagesAdapter.setDatas(contentJsonArray);
					} else {

						if (result.getDatas() == null || result.getDatas().length() <= 0) {
							page--;
						} else {
							try {
								contentJsonArray = AppKit.joinJSONArray(contentJsonArray, result.getDatas());
								companyPagesAdapter.appendDatas(result.getDatas());
							} catch (JSONException e) {
								Log.e(TAG, e.getMessage(), e);
							}
						}

					}

					listview.onRefreshComplete();
				} else {
					emptyview.setText("加载失败，请稍后重试");
					listview.onRefreshComplete();
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				emptyview.setText("加载失败，请稍后重试");

				listview.onRefreshComplete();
			}
		}, this);

	}

	/**
	 * 
	 * 加载企业产品列表
	 * 
	 * 
	 * @author yyh Created at 2015-11-11 下午3:14:18
	 */
	private void getproduct() {
		ApiParam param = ApiParam.create();
		param.addParam("cid", cid);
		param.addParam("page", page);
		if (time != 0) {
			param.addParam("time", time);
		}

		Api.get("enterprise/products", param, new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {

				if (result.getCode() == 100) {
					productJsonArray = result.getDatas();
					adapter = new ColumMainProductImgAdapter(CompanyPagesActivity.this, productJsonArray);
					if (productJsonArray.length() > 0) {
						relativeLayout.setVisibility(View.VISIBLE);

						LayoutParams par = horizontialListview.getLayoutParams();
						View view = adapter.getView(0, null, horizontialListview);
						view.measure(0, 0);
						par.height = view.getMeasuredHeight();

						horizontialListview.setLayoutParams(par);
					}
					horizontialListview.setAdapter(adapter);
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	/**
	 * 初始化绑定
	 * 
	 * 
	 * @author lkx Created at 2015-10-10 上午10:48:42
	 */
	private void ininView() {
		title.setTitle(name);
		companyPagesSubscribeNumber.setText(peoplenumber + "");
		nameOfEnterprise.setText(name);
		enterpriseSlogan.setText(describe);
		// DisplayImageOptions defaultOptions = new
		// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_img_loadrong)
		// .showImageOnFail(R.drawable.infox_img_loadrong).showImageOnLoading(R.drawable.infox_img_loadrong).cacheInMemory(true)
		// .cacheOnDisc(true).build();
		AppKit.SetNormalImg(imageurl, imageview);
		// ImageLoader.getInstance().displayImage(imageurl, imageview,
		// defaultOptions);

		if (subscription != null && subscription.equals("true")) {
			// 已订阅
			subcriptionTextView.setTag("0");
			subcriptionTextView.setText("取消订阅");
			subcriptionTextView.setBackgroundResource(R.drawable.infox_searchitem_third);
			subcriptionTextView.setTextColor(Color.parseColor("#ffffff"));

		} else if (subscription != null && subscription.equals("false")) {
			// 没订阅
			subcriptionTextView.setTag("1");
			subcriptionTextView.setText("订阅");
			subcriptionTextView.setBackgroundResource(R.drawable.infox_orange_frame);
			subcriptionTextView.setTextColor(Color.parseColor("#fa6400"));
		} else {
			subcriptionTextView.setVisibility(View.GONE);
		}
		subcriptionTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(CompanyPagesActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(CompanyPagesActivity.this, LoginActivity.class);
					CompanyPagesActivity.this.startActivity(intent);
					return;
				}

				if (view.getTag().equals("0")) {
					// quxiao
					submit("2");
					subcriptionTextView.setTag("1");
					subcriptionTextView.setText("订阅");
					subcriptionTextView.setBackgroundResource(R.drawable.infox_orange_frame);
					subcriptionTextView.setTextColor(Color.parseColor("#fa6400"));
					ToastKit.showShort(getApplicationContext(), "已取消");

				} else if (view.getTag().equals("1")) {
					// dingyue
					submit("1");
					subcriptionTextView.setTag("0");
					subcriptionTextView.setText("取消订阅");
					subcriptionTextView.setBackgroundResource(R.drawable.infox_searchitem_third);
					subcriptionTextView.setTextColor(Color.parseColor("#ffffff"));

					ToastKit.showShort(getApplicationContext(), "已订阅成功");
				}

			}
		});
		title.titleOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// share

				initSharePupoVindow();
				showPupop();
			}
		});

		call.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (phonenumber == null) {
					return;

				} else if (phonenumber.equals("")) {
					ToastKit.showShort(getApplicationContext(), "该企业暂无客服电话");
					return;
				} else {
					Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phonenumber));
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}

			}
		});
		ask.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 咨询农技
				ToastKit.showShort(CompanyPagesActivity.this, Const.UN_FINISH_ALERT);
			}
		});
		moreTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// ToastKit.showShort(CompanyPagesActivity.this,
				// Const.UN_FINISH_ALERT);
				Intent intent = new Intent(CompanyPagesActivity.this, AllproductActivity.class);
				intent.putExtra("cid", cid);
				startActivity(intent);

			}
		});

	}

	protected void submit(String type) {

		Api.post("me/followEnterprise", ApiParam.create().addParam("id", cid).addParam("type", type), new ApiCallback(this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {

					Intent intent = new Intent();
					intent.setAction(Const.REFLASH);
					CompanyPagesActivity.this.sendBroadcast(intent);
					Log.e("companypage", "ok");
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	@Override
	public void onClick(View view) {
		String content = "《" + name + "》" + "你不可错过的农资精品企业";
		String url = "http://info.nzdb.com.cn/app";

		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(CompanyPagesActivity.this, Const.SP_KEY_USER_ID))) {
			try {
				url = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl") + "?code="
						+ SharedPreferencesKit.getString(this, Const.USER_InvitedCode) + "&mid="
						+ SharedPreferencesKit.getString(this, Const.SP_KEY_USER_MID);
			} catch (Exception e) {

			}

		}
		switch (view.getId()) {
		case R.id.shareToWeixin:
			shareTo = SHARE_MEDIA.WEIXIN;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToFriendCircle:
			shareTo = SHARE_MEDIA.WEIXIN_CIRCLE;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToMessage:
			shareTo = SHARE_MEDIA.SMS;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToQQ:
			shareTo = SHARE_MEDIA.QQ;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToWeb:
			shareTo = SHARE_MEDIA.SINA;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareEmail:
			shareTo = SHARE_MEDIA.EMAIL;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.transpond:
			ToastKit.showShort(getApplicationContext(), Const.UN_FINISH_ALERT);
			break;
		case R.id.shareCopyLink:

			ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			if (Build.VERSION.SDK_INT >= 11) {
				ClipData clipData = ClipData.newPlainText("App下载链接", url);
				clip.setPrimaryClip(clipData);
			} else {
				clip.setText(url);
			}

			break;
		case R.id.cancle:
			mPopupWindow.dismiss();
			break;

		}

	}

	private void initSharePupoVindow() {

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_activity_content_share_popu, null);

		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
		popupWindow.findViewById(R.id.shareToWeixin).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToFriendCircle).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToMessage).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToQQ).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToWeb).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareEmail).setOnClickListener(this);
		popupWindow.findViewById(R.id.transpond).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareCopyLink).setOnClickListener(this);
		popupWindow.findViewById(R.id.cancle).setOnClickListener(this);
	}

	private void showPupop() {

		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow.showAtLocation(findViewById(R.id.id_parent), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}

	}

}
